using System;
using UnityEngine;
using UnityEngine.InputSystem;
using Random = UnityEngine.Random;

public class PlayerController : MonoBehaviour
{
    private BoardManager m_Board;
    private Vector2Int m_CellPosition;
    private Vector2Int m_TryToMovePosition;
    private bool m_Inputalbe = true;
    private bool m_willMoved = false;
    [SerializeField, Utility.Attributes.NotNull] private Utility.GameEvents.Scriptable.Integrated.VoidGameEvent m_playerTurnDoneEvent;
    public Utility.GameEvents.Scriptable.Integrated.VoidGameEvent PlayerTurnDoneEvent => m_playerTurnDoneEvent;
    
    public Vector2Int CurrentCellPosition => m_CellPosition;
    private void Update() {
        
        if(!m_Board) return;
        checkInput();
    }

    public void Init(BoardManager board, Vector2Int startCell) {
        this.m_Board = board;
        this.m_CellPosition = startCell;

        Spawn();
    }

    private void checkInput() {
        if (m_Inputalbe) {
            if (Keyboard.current.aKey.wasPressedThisFrame || Keyboard.current.leftArrowKey.wasPressedThisFrame) {
                m_TryToMovePosition = m_CellPosition + new Vector2Int(-1, 0);
                m_willMoved = true;
            }
            else if (Keyboard.current.dKey.wasPressedThisFrame || Keyboard.current.rightArrowKey.wasPressedThisFrame) {
                m_TryToMovePosition = m_CellPosition + new Vector2Int(1, 0);
                m_willMoved = true;
            }
            else if (Keyboard.current.wKey.wasPressedThisFrame || Keyboard.current.upArrowKey.wasPressedThisFrame) {
                m_TryToMovePosition = m_CellPosition + new Vector2Int(0, 1);
                m_willMoved = true;
            }
            else if (Keyboard.current.sKey.wasPressedThisFrame || Keyboard.current.downArrowKey.wasPressedThisFrame) {
                m_TryToMovePosition = m_CellPosition + new Vector2Int(0, -1);
                m_willMoved = true;
            }
            
            if (m_Board.IsThisCellMovealbe(m_TryToMovePosition) && m_willMoved) {
                m_CellPosition = m_TryToMovePosition;
                moveToCell();
                m_willMoved = false;
            }
        }
    }

    private void moveToCell() {
        transform.position = m_Board.CellToWorld(m_CellPosition);
        m_playerTurnDoneEvent.Raise();
    }

    private void Spawn()
    {
        moveToCell();
        m_Inputalbe = true;
    }
}
